#coding: utf-8
'''This module provides several tools for general use.
'''

import os, time

class Debugger():
    '''Use for debugging.
    '''
    def __init__(self, isDebug=False, mode="std"):
        self.debug = isDebug
        self.bugInfo = ""
        self.mode = mode
        self.time = time.strftime("%H-%M-%S", time.localtime())

    def dPrint(self, s):
        if self.debug:
            if self.mode != "std":
                f = open("debug-log-%s" % (self.time), 'a')
                f.write(s)
                f.close()
            else:
                print(s)
            s = ""

    def checkError(self, err):
        self.bugInfo = '\n\n'
        for funct in err:
            self.bugInfo += funct + ":"
            if len(err[funct]) == 0:
                self.bugInfo += "\nPass\n"
            else:
                self.bugInfo += "%d Error(s)\n" % (len(err[funct]))
                for info in err[funct]:
                    self.bugInfo += info + "\n"
            self.bugInfo += "\n"
        self.dPrint(self.bugInfo)

class SystemTools(Debugger):
    '''Several system tools.
    '''
    def __init__(self, isDebug, mode='std'):
        Debugger.__init__(self, isDebug, mode)
        self.errorRecord = set()
        self.footprint = set()

    def customizedCMD(self, cmd):
        if os.system(cmd):
            self.errorRecord.add(cmd)

    def customizedMkDir(self, path):
        '''Create folders recursively if not existed.
        '''
        if os.path.exists(path):
            return
        os.makedirs(path)

    def osWalk(self, rootPath, funct, limit=(lambda parent, fileName: True),\
            error=IOError, **argv):
        '''Important osWalk function for scanning.
        '''
        self.dPrint(rootPath)
        for parent, dirNames, fileNames in os.walk(rootPath):
            for fileName in fileNames:
                if fileName in self.footprint:
                    continue
                if limit(parent, fileName) == False:
                    continue
                try:
                    funct(os.path.join(parent, fileName), **argv)
                except error as e:
                    self.errorRecord.add(str(e))
                self.footprint.add(fileName)
            for dirName in dirNames:
                self.osWalk(os.path.join(parent, dirName), funct, \
                        limit=limit, error=error, **argv)



if __name__ == "__main__":
    pass
